
import Home from "@/layout/index.tsx";
// 重定向Navigate,
// 获取当先路径对象useLocation
import { Navigate, useNavigate, useRoutes,} from "react-router-dom";
// 两种路由模式，BrowserRouter（history模式），HashRouter(Hash模式)
// 路由懒加载，需要增加其他写法 { path:'/about', element:<React.Suspense fallback={<div>Loading...</div>}><About/></React.Suspense>}
import React, {useEffect, useState} from "react"
import RouteGuard from "./routeGuard.tsx";
import Login from "../views/login.tsx";


import {WithLoadingComponent, addRouteToMenu} from "./routerUtils.tsx";
import {getRouters} from "../api/system/menu.ts";
import {getToken} from "../utils/auth.ts";
import {SET_ROUTER} from "../store/modules/routerStore.ts";
import { useAppDispatch } from "@/store/index.tsx";

// 动态路由，基于用户权限动态去加载,
const dynamicRoutes = [
    {
        path: '/system/role-auth/user/:roleId',
        element: WithLoadingComponent('system/role/component/authRole/authRole')
    },
    {
        path: '/system/dict-data/index/:dictId',
        element: WithLoadingComponent('system/dict/component/DictionaryData/index')
    },

]

// 基础路由
const router:any[] = [
    {
        path: '/',
        element: <Navigate to="/Home"/>
    },
    {
        path: '/login',
        element: <Login/>
    },
    {
        path: '/',
        element: <RouteGuard><Home/></RouteGuard>,
        children: [
            {
                path: '/Home',
                element: WithLoadingComponent('Home/index')
            },

            ...dynamicRoutes
        ]
    },
    // 访问其余路径的时候直接跳转到这个页面
    {
        path: "*",
        element: WithLoadingComponent('test/404')
    }
];




// 合并路由
function mergeRouterList(List:any[]) {
    router[2].children = router[2].children.concat(List)

    return router;
}

const Routes = () => {
    // 默认基础路由数据
    const [routerLists, setRouterLists] = useState(router)
    // 用于判断接口是否调取完成.避免路由未添加上就渲染.导致找不到路由
    const [loading, setLoading] = useState(true)
    // 将路由数据存起来到redux
    const dispatch = useAppDispatch()

    const token = getToken()

    const navigator=useNavigate()

    useEffect(() => {
        if(token){
        getRouters().then((res:any) => {

            setLoading(false)
            // 存到redux中
            dispatch(SET_ROUTER(res.data))
            // 合并原始路由和接口路由
            setRouterLists(mergeRouterList(addRouteToMenu(res.data) ))
            // console.log(routerLists,'routerLists')
            // 判断是否登录过期，过期跳转到登录页面，拦截器是一个js文件，不支持react的模块化
            if(res.code==="401"){

                navigator('/login')
            }
        }).catch((error) => {
        })
        }
    }, [token])

    // 添加到useRoutes钩子函数中
    const rout = useRoutes(routerLists)
    // 1.1如果包含token代表登录，走登录逻辑
    // 1.2登录后可能会有接口未响应完全的情况
    // 2.否则直接返回原始路由的
    if (token) {
        if (loading) {
            return (<div>loading....</div>)
        } else {
            return rout;
        }
    } else {

        return rout;
    }


}


export default Routes
